﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;

namespace ArgusPCLib.Reflection
{
	public static class Parser
	{
		public static Func<string, object> GetParseHandler(Type type)
		{
			IEnumerable<MethodInfo> mis = type.GetRuntimeMethods();
			foreach (MethodInfo mi in mis)
			{
				if (!mi.IsStatic)
					continue;
				if (!mi.ReturnType.Is(type))
					continue;

				Type[] parameterTypes = mi.GetParameterTypes();
				if (parameterTypes.Length == 1 && parameterTypes[0] == typeof(string))
				{
					return new Func<string, object>((text) => { return mi.Invoke(null, new object[] { text }); });
				}
				else if (parameterTypes.Length == 2 && parameterTypes[0] == typeof(string) && parameterTypes[1] == typeof(IFormatProvider))
				{
					return new Func<string, object>((text) => { return mi.Invoke(null, new object[] { text, System.Globalization.CultureInfo.InvariantCulture }); });
				}
			}
			return null;
		}

		public static Func<string,T> GetParseHandler<T>()
		{
			return new Func<string, T>((text) => { return (T)Parser.GetParseHandler(typeof(T))(text); });
		}
	}
}
